package com.example.controller;

import com.example.service.FutureExampleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

@RestController
@RequestMapping("/future/example")
public class FutureExampleController {

    @Autowired
    private FutureExampleService futureExampleService;

    @GetMapping("/future-task")
    public String futureTask() throws ExecutionException, InterruptedException {
        Future<String> result = futureExampleService.executeTask();
        // 等待任务完成
        return result.get();
    }

    @GetMapping("/cancel-task")
    public String cancelTask() throws InterruptedException {
        futureExampleService.cancelTask();
        return "任务取消成功";
    }

    @GetMapping("/check-task")
    public String checkTask() throws InterruptedException {
        futureExampleService.checkIfTaskIsDone();
        return "任务检查完成";
    }

    @GetMapping("/multiple-tasks")
    public String multipleTasks() throws InterruptedException {
        futureExampleService.executeMultipleTasks();
        return "多个任务已执行完成";
    }

    @GetMapping("/any-task")
    public String anyTask() {
        futureExampleService.executeAnyTask();
        return "最先完成的任务已获取结果";
    }

    @GetMapping("/shutdown-executor")
    public String shutdownExecutor() {
        futureExampleService.shutdownExecutor();
        return "线程池已关闭";
    }
}
